package org.dromara.assets.biz;

import lombok.extern.slf4j.Slf4j;
import org.dromara.assets.service.impl.TradePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class ScheduledTask {

    @Autowired
    BinanceBiz binanceBiz;

    // 定义一个信号量，用于控制任务是否正在运行
    private final AtomicBoolean isRunning = new AtomicBoolean(false);

    @Scheduled(fixedRate = 2 * 60 * 1000) // 每隔2分钟执行一次
    public void executeTask() {
        if (isRunning.get()) {
            log.warn("上一次任务尚未完成，跳过本次调度...");
            return;
        }
        isRunning.set(true);
        syncTradeRecordBinance();
    }

    @Autowired
    private TradePlanService tradePlanService;

    @Scheduled(fixedRate = 30 * 1000)
    public void scheduleTradePlanProcessing() throws Exception {
        tradePlanService.processTradePlans();
    }

    // 模拟一个耗时任务
    void syncTradeRecordBinance() {
        try {
            binanceBiz.syncTradeRecordBinance();
        } catch (Exception e) {
            log.error("任务异常", e);
        } finally {
            isRunning.set(false);
        }
    }
}
